<template>
  <div ref="chartRef" class="chart" />
</template>

<script setup>
import { onMounted, onUnmounted, ref, watch, nextTick } from "vue";
import * as echarts from "echarts";
// import * as echarts from 'echarts/core';
// import { TooltipComponent, LegendComponent } from 'echarts/components';
// import { GraphChart } from 'echarts/charts';
// import { LabelLayout } from 'echarts/features';
// import { CanvasRenderer } from 'echarts/renderers';
// echarts.use([
//   TooltipComponent,
//   LegendComponent,
//   GraphChart,
//   CanvasRenderer,
//   LabelLayout
// ]);

const chartRef = ref(Math.random().toString(36).slice(2, 10));
let chartInstance = null;
const props = defineProps({
  options: {
    type: Object,
    required: true
  }
});
onMounted(() => {
  window.addEventListener("resize", handelResize);
});
const handelResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};
const updateOptionFunc = newOptions => {
  let id = -1;
  newOptions.series[0].data.forEach(v => {
    if (v.isCenter) {
      v.x = chartInstance.getWidth() / 2;
      v.y = chartInstance.getHeight() / 2;
      v.fixed = true;
      id = v.id;
    } else {
      v.x = undefined;
      v.y = undefined;
      v.fixed = undefined;
    }
  });
  chartInstance.setOption(newOptions);
  chartInstance.dispatchAction({
    type: "graphRoam", // 视图操作类型
    zoom: 2, // 放大比例（2倍）
    originX: chartInstance.getWidth() / 2, // 以目标节点为中心点
    originY: chartInstance.getHeight() / 2
  });
  console.log("w", chartInstance.getWidth() / 2);
  console.log("h", chartInstance.getHeight() / 2);
  if (id != -1) {
    chartInstance.dispatchAction({
      type: "highlight",
      seriesIndex: 0, // 系列索引（第一个系列）
      dataIndex: id - 1 // 节点索引（对应 data 数组中的位置）
    });
  }

  chartInstance.resize();
};
const initChart = newOptions => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value);
    chartInstance.clear();
    chartInstance.setOption(newOptions);
  }
};
const getChartPos = () => {
  let w = chartInstance?.getWidth() || 0;
  let h = chartInstance?.getHeight() || 0;
  return {
    width: w,
    height: h
  };
};
const zoomCenterNode = (x, y) => {
  chartInstance?.dispatchAction({
    type: "graphRoam", // 视图操作类型
    zoom: 2, // 放大比例（2倍）
    originX: x, // 以目标节点为中心点
    originY: y
  });
};
watch(
  () => props.options,
  newOptions => {
    console.log(newOptions);
    if (chartInstance) {
      chartInstance = echarts.init(chartRef.value);
      chartInstance.clear();
      updateOptionFunc(newOptions);
    } else {
      initChart(newOptions);
    }
  }
);
onUnmounted(() => {
  chartInstance && chartInstance.dispose();
  window.removeEventListener("resize", handelResize);
});
defineExpose({
  getChartPos,
  chartInstance,
  zoomCenterNode
});
</script>

<style scoped lang="scss">
.chart {
  width: 100%;
  height: 100%;
}
</style>
